import {Injectable} from '@nestjs/common';
import {Bookmark, BookmarkTagsHoard} from './bookmark.entity'
import {InjectRepository} from "@nestjs/typeorm";
import {Repository} from "typeorm";
import {pagination} from "../utils/pagination";
import {Category} from "./category/category.entity";

const {
    bookmarkTitleExpire,
    bookmarkLinkExpire,
    bookmarkCategoryidExpire,
    bookmarkErrExpire,
    bookmarkIDExpire,
    bookmarkNoTagsHoard
} = require('../provider/error')

@Injectable()
export class BookmarkService {
    constructor(
        @InjectRepository(Category) private category: Repository<Category>,
        @InjectRepository(Bookmark) private bookmark: Repository<Bookmark>,
        @InjectRepository(BookmarkTagsHoard) private bookmarkTagsHoard: Repository<BookmarkTagsHoard>,
    ) {
    }

    async bookmarkList(request) {
        const res: any = await pagination(request, this.bookmark, 'bookmark')
        return res
    }

    async createBookmark(bodyData) {
        if (!bodyData.user_id || bodyData.user_id == '') return bookmarkErrExpire()
        if (!bodyData.title || bodyData.title == '') return bookmarkTitleExpire()
        if (!bodyData.link || bodyData.link == '') return bookmarkLinkExpire()
        if (!bodyData.category_id || bodyData.category_id == '') return bookmarkCategoryidExpire()

        await this.bookmark.save({
            ...bodyData,
            tags_num: 0,
            hoard_num: 0,
            pv: 0,
            create_time: new Date(),
            updated_time: new Date(),
        })
        return []
    }

    async updateBookmark(bodyData) {
        if (!bodyData.user_id || bodyData.user_id == '') return bookmarkErrExpire()
        if (!bodyData.id || bodyData.id == '') return bookmarkIDExpire()
        if (!bodyData.title || bodyData.title == '') return bookmarkTitleExpire()
        if (!bodyData.link || bodyData.link == '') return bookmarkLinkExpire()
        if (!bodyData.category_id || bodyData.category_id == '') return bookmarkCategoryidExpire()
        const res = await this.bookmark.update(bodyData.id, {
            ...bodyData,
            updated_time: new Date(),
        })
        if (res.affected !== 1) return bookmarkErrExpire()

        return []
    }

    async delBookmark(params) {
        if (!params.id || params.id == '') return bookmarkIDExpire()
        const res = await this.bookmark.delete(params.id)
        if (res.affected !== 1) return bookmarkErrExpire()
        return []
    }

    async getBookmarkList() {
        const bookmarkList = await this.bookmark.createQueryBuilder("bookmark").addOrderBy('sort', 'DESC').getMany()
        const categoryList = await this.category.createQueryBuilder("category").addOrderBy('sort', 'DESC').getMany()
        const bookmarkType = await this.bookmarkTagsHoard.createQueryBuilder("bookmarkTagsHoard").getMany()
        console.log('bookmarkType', bookmarkType)
        const data = []
        // const initTree = () => {
        //     return categoryList.map(t => {
        //
        //     })
        // }

        const newBookmarkList = []
        bookmarkList.forEach(c => {
            const Obj = {
                ...c,
                tags: 0,
                hoard: 0
            }
            bookmarkType.forEach(t => {
                if (t.bookmark_id == c.id) {
                    Obj.tags = t.tags
                    Obj.hoard = t.hoard
                }
            })
            newBookmarkList.push(Obj)
        })
        categoryList.forEach(item => {
            const dataObj = {
                category_id: item.id,
                category_name: item.name,
                icon: item.icon,
                bookmark: newBookmarkList.filter(t => t.category_id == item.id),
            }
            data.push(dataObj)
        })
        return data
    }

    async addBookmarkPv(queryData: { id: string }) {
        if (!queryData.id) return bookmarkIDExpire()
        let pvResult = await this.bookmark.findOne({where: {id: queryData.id}, select: ['pv']})
        const pv = pvResult.pv + 1
        const res = await this.bookmark.update(queryData.id, {
            pv
        })
        if (res.affected !== 1) return bookmarkErrExpire()
        return []
    }

    async bookmarkHoard(queryData) {
        const {user_id, tags, hoard} = queryData
        if (!queryData.id) return bookmarkIDExpire()
        const findOne = await this.bookmarkTagsHoard.findOne({
            where: {
                user_id: user_id,
                bookmark_id: queryData.id
            }
        })
        if (findOne) {
            let data = {}
            if (tags) {
                data = {tags}
            } else {
                data = {hoard}
            }
            await this.bookmarkTagsHoard.update(findOne.id, {
                ...data,
                updated_time: new Date(),
            })
        } else {
            let data = {}
            if (tags) {
                data = {tags}
            } else {
                data = {hoard}
            }
            await this.bookmarkTagsHoard.save({
                ...data,
                user_id: user_id,
                bookmark_id: queryData.id,
                create_time: new Date(),
                updated_time: new Date(),
            })
        }
        return []
    }
}


